<template>
  <div class="doctor-schedule">
    <!-- 医生ID获取失败时的提示卡片 -->
    <el-card shadow="never" v-if="doctorIdFailed">
      <template #header>
        <div class="card-header">
          <h2>无法获取医生信息</h2>
        </div>
      </template>
      
      <div class="error-container">
        <el-alert
          title="无法获取医生信息"
          type="error"
          description="系统无法获取您的医生信息，请确保您已经以医生身份登录。"
          show-icon
          :closable="false"
        />
        <div class="error-actions">
          <el-button type="primary" @click="retryGetDoctorId">重试</el-button>
          <el-button @click="goToLogin">返回登录</el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 排班管理主要内容 -->
    <el-card shadow="never" v-else>
      <template #header>
        <div class="card-header">
          <h2>我的排班管理</h2>
          <div>
            <el-button type="primary" @click="handleAddSchedule">
              <el-icon><Plus /></el-icon> 添加排班
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索和筛选区域 -->
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" size="small" class="filter-container">
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
            style="width: 320px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 排班表格 -->
      <el-table
        v-loading="loading"
        :data="scheduleList"
        style="width: 100%"
        border
        stripe
        row-key="id"
        :cell-style="{padding: '8px'}"
        table-layout="auto"
      >
        <el-table-column label="排班日期" min-width="110" prop="date">
          <template #default="scope">
            <span class="date-display">{{ formatDateDisplay(scope.row.date) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时间段" min-width="240">
          <template #default="scope">
            <div v-for="slot in scope.row.timeSlots" :key="slot.period" class="time-slot-item">
              <el-tag size="small" :type="getTimeSlotType(slot.period)">{{ slot.period }}</el-tag>
              <span class="time-slot-detail">{{ slot.startTime }}-{{ slot.endTime }}</span>
              <span class="capacity-info">
                (容量: {{ slot.capacity }})
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="剩余号源" min-width="130">
          <template #default="scope">
            <div v-for="(capacity, period) in scope.row.remainingCapacity" :key="period" class="remaining-item">
              <span>{{ period }}：</span>
              <el-tag :type="getCapacityTagType(capacity, scope.row.timeSlots.find(s => s.period === period)?.capacity)">
                {{ capacity }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="诊室" prop="room" min-width="100" />
        <el-table-column label="挂号类型" min-width="120">
          <template #default="scope">
            <el-tag>{{ scope.row.registrationType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="150" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="small"
                @click="handleView(scope.row)"
              >
                查看
              </el-button>
              <el-button 
                type="danger" 
                size="small"
                @click="handleCancel(scope.row)"
                :disabled="scope.row.status !== '正常'"
              >
                取消
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增排班对话框 -->
    <el-dialog
      v-model="scheduleDialogVisible"
      :title="isEdit ? '编辑排班' : '新增排班'"
      width="600px"
    >
      <el-form 
        ref="scheduleFormRef" 
        :model="scheduleForm" 
        :rules="scheduleRules" 
        label-width="100px"
      >
        <el-form-item label="排班日期" prop="date">
          <el-date-picker
            v-model="scheduleForm.date"
            type="date"
            placeholder="选择排班日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate"
          />
        </el-form-item>
        
        <el-form-item label="时间段" prop="timeSlots">
          <div class="time-slots-container">
            <p class="time-slot-hint">上午时段:</p>
            <el-checkbox-group v-model="scheduleForm.timeSlots" class="time-slot-group">
              <el-checkbox-button 
                v-for="slot in morningTimeSlots" 
                :key="slot.value" 
                :label="slot.value"
              >
                {{ slot.label }}
              </el-checkbox-button>
            </el-checkbox-group>
            
            <p class="time-slot-hint">下午时段:</p>
            <el-checkbox-group v-model="scheduleForm.timeSlots" class="time-slot-group">
              <el-checkbox-button 
                v-for="slot in afternoonTimeSlots" 
                :key="slot.value" 
                :label="slot.value"
              >
                {{ slot.label }}
              </el-checkbox-button>
            </el-checkbox-group>
          </div>
          <div class="form-tips">
            选择您在该日期可出诊的时间段
          </div>
        </el-form-item>
        
        <el-form-item label="诊室" prop="room">
          <el-select v-model="scheduleForm.room" placeholder="请选择诊室" style="width: 100%">
            <el-option label="诊室1" value="诊室1" />
            <el-option label="诊室2" value="诊室2" />
            <el-option label="诊室3" value="诊室3" />
            <el-option label="诊室4" value="诊室4" />
            <el-option label="诊室5" value="诊室5" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="挂号类型" prop="registrationType">
          <el-select v-model="scheduleForm.registrationType" placeholder="请选择挂号类型" style="width: 100%">
            <el-option label="普通门诊" value="普通门诊" />
            <el-option label="专家门诊" value="专家门诊" />
            <el-option label="特需门诊" value="特需门诊" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="最大预约数" prop="maxAppointments">
          <el-input-number
            v-model="scheduleForm.maxAppointments"
            :min="0"
            :max="100"
            placeholder="不填则无限制"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="备注" prop="notes">
          <el-input 
            v-model="scheduleForm.notes" 
            type="textarea" 
            placeholder="请输入备注信息（可选）" 
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="scheduleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitScheduleForm" :loading="submitLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 取消排班对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消排班"
      width="500px"
    >
      <div class="cancel-warning">
        <el-alert
          title="取消排班将会影响已预约的患者"
          type="warning"
          description="取消排班后，该时段内的所有预约将被标记为已取消，并通知相关患者。"
          show-icon
          :closable="false"
        />
      </div>
      
      <el-form :model="cancelForm" ref="cancelFormRef" label-width="100px">
        <el-form-item label="取消原因" prop="reason" required>
          <el-input
            v-model="cancelForm.reason"
            type="textarea"
            placeholder="请输入取消原因"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancel" :loading="cancelLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { scheduleAPI, doctorAPI } from '@/utils/api'
import { formatDate } from '@/utils/date'
import { useUserStore } from '@/stores/user'
import { Plus } from '@element-plus/icons-vue'

// 路由实例
const router = useRouter()
const userStore = useUserStore()

// 数据加载状态
const loading = ref(false)
const submitLoading = ref(false)
const cancelLoading = ref(false)

// 表格数据
const scheduleList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchFormRef = ref(null)
const searchForm = reactive({
  startDate: '',
  endDate: ''
})

// 日期范围
const dateRange = ref([])

// 对话框显示状态
const scheduleDialogVisible = ref(false)
const cancelDialogVisible = ref(false)
const isEdit = ref(false)

// 排班表单
const scheduleFormRef = ref(null)
const scheduleForm = reactive({
  date: '',
  timeSlots: [],
  room: '',
  registrationType: '普通门诊',
  maxAppointments: undefined,
  notes: ''
})

// 取消排班表单
const cancelFormRef = ref(null)
const cancelForm = reactive({
  scheduleId: '',
  reason: ''
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '本周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * start.getDay())
      return [start, end]
    },
  },
  {
    text: '下周',
    value: () => {
      const now = new Date()
      const start = new Date()
      start.setTime(now.getTime() + 3600 * 1000 * 24 * (7 - now.getDay()))
      const end = new Date()
      end.setTime(start.getTime() + 3600 * 1000 * 24 * 6)
      return [start, end]
    },
  },
  {
    text: '本月',
    value: () => {
      const now = new Date()
      const start = new Date(now.getFullYear(), now.getMonth(), 1)
      const end = new Date(now.getFullYear(), now.getMonth() + 1, 0)
      return [start, end]
    },
  },
]

// 时间段选项
const timeSlotOptions = [
  { label: '08:00-09:00', value: '08:00-09:00' },
  { label: '09:00-10:00', value: '09:00-10:00' },
  { label: '10:00-11:00', value: '10:00-11:00' },
  { label: '11:00-12:00', value: '11:00-12:00' },
  { label: '14:00-15:00', value: '14:00-15:00' },
  { label: '15:00-16:00', value: '15:00-16:00' },
  { label: '16:00-17:00', value: '16:00-17:00' },
  { label: '17:00-18:00', value: '17:00-18:00' }
]

// 上午时间段
const morningTimeSlots = [
  { label: '08:00-09:00', value: '08:00-09:00' },
  { label: '09:00-10:00', value: '09:00-10:00' },
  { label: '10:00-11:00', value: '10:00-11:00' },
  { label: '11:00-12:00', value: '11:00-12:00' }
]

// 下午时间段
const afternoonTimeSlots = [
  { label: '14:00-15:00', value: '14:00-15:00' },
  { label: '15:00-16:00', value: '15:00-16:00' },
  { label: '16:00-17:00', value: '16:00-17:00' },
  { label: '17:00-18:00', value: '17:00-18:00' }
]

// 表单验证规则
const scheduleRules = {
  date: [
    { required: true, message: '请选择排班日期', trigger: 'change' }
  ],
  timeSlots: [
    { required: true, message: '请至少选择一个时间段', trigger: 'change' }
  ],
  room: [
    { required: true, message: '请输入诊室', trigger: 'blur' }
  ],
  registrationType: [
    { required: true, message: '请选择挂号类型', trigger: 'change' }
  ]
}

// 禁用的日期（今天之前的日期不可选）
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
}

// 监听日期范围变化
const updateDateRange = computed(() => {
  if (dateRange.value && dateRange.value.length === 2) {
    searchForm.startDate = dateRange.value[0]
    searchForm.endDate = dateRange.value[1]
  } else {
    searchForm.startDate = ''
    searchForm.endDate = ''
  }
})

// 获取时间段标签类型
const getTimeSlotType = (period) => {
  switch (period) {
    case '上午':
      return 'success'
    case '下午':
      return 'warning'
    case '晚上':
      return 'info'
    default:
      return ''
  }
}

// 获取剩余号源标签类型
const getCapacityTagType = (remaining, total) => {
  if (!total) return 'info'
  const ratio = remaining / total
  if (ratio <= 0.2) return 'danger'
  if (ratio <= 0.5) return 'warning'
  return 'success'
}

// 医生ID获取失败标志
const doctorIdFailed = ref(false)

// 获取当前医生ID
const getCurrentDoctorId = async () => {
  try {
    // 获取当前登录用户信息
    const userInfo = userStore.userInfo
    console.log('当前用户信息:', userInfo)
    
    // 如果userInfo中有doctorId，直接使用
    if (userInfo && (userInfo.doctorId || userInfo.doctor)) {
      const doctorId = userInfo.doctorId || userInfo.doctor
      console.log('从userInfo中获取到doctorId:', doctorId)
      return doctorId
    }
    
    // 获取用户ID
    const userId = userStore.userId || userInfo?.id || userInfo?._id
    console.log('当前用户ID:', userId)
    
    if (!userId) {
      ElMessage.error('用户未登录或无法获取用户ID')
      return null
    }

    // 通过用户ID获取医生信息
    const res = await doctorAPI.getDoctorByUserId(userId)
    console.log('通过用户ID获取医生信息结果:', res)
    
    if (res.success && res.data) {
      const doctorId = res.data.id || res.data._id
      console.log('获取到医生ID:', doctorId)
      return doctorId
    } else {
      // 尝试获取工作站组件中已获取的医生ID
      if (window.doctorId) {
        console.log('从window.doctorId获取:', window.doctorId)
        return window.doctorId
      }
      
      // 尝试从URL参数中获取
      const urlParams = new URLSearchParams(window.location.search)
      const doctorIdFromUrl = urlParams.get('doctorId')
      if (doctorIdFromUrl) {
        console.log('从URL参数获取doctorId:', doctorIdFromUrl)
        return doctorIdFromUrl
      }
      
      // 如果以上方法都失败，则显示错误
      ElMessage.error('获取医生信息失败')
      return null
    }
  } catch (error) {
    console.error('获取医生ID失败:', error)
    
    // 尝试从工作站共享变量获取
    if (window.doctorId) {
      console.log('异常处理中从window.doctorId获取:', window.doctorId)
      return window.doctorId
    }
    
    ElMessage.error('获取医生信息失败，请重新登录')
    return null
  }
}

// 获取医生所属科室ID
const getDoctorDepartment = async () => {
  try {
    // 获取当前医生ID
    const doctorId = await getCurrentDoctorId()
    if (!doctorId) {
      return null;
    }
    
    // 获取医生详情
    const res = await doctorAPI.getDoctor(doctorId)
    if (res.success && res.data) {
      const departmentId = res.data.departmentId || res.data.department || null;
      // 存储到window对象以便在其他地方使用
      window.departmentId = departmentId;
      console.log('获取到医生所属科室:', departmentId);
      return departmentId;
    }
    return null;
  } catch (error) {
    console.error('获取医生所属科室失败:', error);
    return null;
  }
}

// 获取排班列表
const getSchedules = async () => {
  loading.value = true
  try {
    // 获取当前医生ID
    const doctorId = await getCurrentDoctorId()
    if (!doctorId) {
      loading.value = false
      doctorIdFailed.value = true  // 设置获取失败标志
      return
    }

    doctorIdFailed.value = false  // 重置失败标志

    // 构建查询参数
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      doctorId: doctorId,
      ...searchForm
    }
    
    // 移除空字段
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    // 调用API获取排班数据
    const res = await scheduleAPI.getSchedules(params)
    if (res.success && res.data) {
      scheduleList.value = res.data.schedules || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error('获取排班列表失败')
    }
  } catch (error) {
    console.error('获取排班列表失败:', error)
    ElMessage.error('获取排班列表失败')
    doctorIdFailed.value = true  // 设置获取失败标志
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1
  getSchedules()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value.resetFields()
  dateRange.value = []
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  getSchedules()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  getSchedules()
}

// 添加排班
const handleAddSchedule = () => {
  isEdit.value = false
  scheduleForm.date = ''
  scheduleForm.timeSlots = []
  scheduleForm.room = ''
  scheduleForm.registrationType = '普通门诊'
  scheduleForm.maxAppointments = undefined
  scheduleForm.notes = ''
  scheduleDialogVisible.value = true
}

// 查看排班
const handleView = (row) => {
  router.push(`/portal/doctor/schedule/${row.id}`)
}

// 取消排班
const handleCancel = (row) => {
  cancelForm.scheduleId = row.id
  cancelForm.reason = ''
  cancelDialogVisible.value = true
}

// 确认取消排班
const confirmCancel = async () => {
  if (!cancelForm.reason) {
    ElMessage.warning('请输入取消原因')
    return
  }
  
  cancelLoading.value = true
  try {
    await scheduleAPI.cancelSchedule(cancelForm.scheduleId, { 
      reason: cancelForm.reason 
    })
    ElMessage.success('排班已取消')
    cancelDialogVisible.value = false
    getSchedules()
  } catch (error) {
    ElMessage.error(error.message || '取消排班失败')
  } finally {
    cancelLoading.value = false
  }
}

// 提交排班表单
const submitScheduleForm = async () => {
  // 表单验证
  const valid = await scheduleFormRef.value.validate().catch(() => false)
  if (!valid) {
    return
  }

  submitLoading.value = true
  try {
    // 获取当前医生ID
    const doctorId = await getCurrentDoctorId()
    if (!doctorId) {
      submitLoading.value = false
      ElMessage.error('无法获取医生信息，请重新登录')
      return
    }

    // 检查所有必填字段
    if (!scheduleForm.date) {
      ElMessage.error('请选择排班日期')
      submitLoading.value = false
      return
    }
    
    if (!scheduleForm.timeSlots || scheduleForm.timeSlots.length === 0) {
      ElMessage.error('请至少选择一个时间段')
      submitLoading.value = false
      return
    }
    
    if (!scheduleForm.room) {
      ElMessage.error('请选择诊室')
      submitLoading.value = false
      return
    }

    // 准备提交数据
    const formData = {
      doctorId,
      date: scheduleForm.date,
      timeSlots: scheduleForm.timeSlots.map(slot => {
        // 如果已经是对象格式且包含所有必需字段，则直接返回
        if (typeof slot === 'object' && slot !== null && 
            slot.startTime && slot.endTime && slot.period) {
          return slot;
        }
        
        // 如果是字符串格式 (如 "08:00-09:00")，则转换为对象格式
        if (typeof slot === 'string' && slot.includes('-')) {
          const [startTime, endTime] = slot.split('-');
          
          // 确定时段
          let period = '上午';
          const hour = parseInt(startTime.split(':')[0]);
          if (hour >= 12 && hour < 18) {
            period = '下午';
          } else if (hour >= 18) {
            period = '晚上';
          }
          
          return {
            startTime,
            endTime,
            period,
            capacity: Number(scheduleForm.maxAppointments) || 10 // 使用maxAppointments作为容量
          };
        }
        return null;
      }).filter(Boolean), // 过滤掉null值
      room: scheduleForm.room,
      registrationType: scheduleForm.registrationType,
      departmentId: window.departmentId || '682c55b57d196017f623bcf0',
      remarks: scheduleForm.notes, // 后端字段是remarks而不是notes
      status: '正常' // 默认状态
    }

    // 发起请求
    let res
    if (isEdit.value) {
      res = await scheduleAPI.updateSchedule(scheduleForm.id, formData)
    } else {
      res = await scheduleAPI.createSchedule(formData)
    }

    if (res.success) {
      ElMessage.success(isEdit.value ? '排班更新成功' : '排班创建成功')
      scheduleDialogVisible.value = false
      getSchedules()
    } else {
      ElMessage.error(res.message || (isEdit.value ? '更新排班失败' : '创建排班失败'))
    }
  } catch (error) {
    console.error('保存排班失败:', error)
    
    // 显示详细的错误信息
    if (error.data && error.data.errors) {
      try {
        // 检查errors结构
        const errorFields = Object.keys(error.data.errors)
        const errorMessages = errorFields.map(field => {
          const fieldError = error.data.errors[field];
          // 处理不同类型的错误消息
          if (Array.isArray(fieldError)) {
            return `${field}: ${fieldError.join(', ')}`;
          } else if (typeof fieldError === 'string') {
            return `${field}: ${fieldError}`;
          } else {
            return `${field}: 验证失败`;
          }
        })
        
        // 显示错误详情
        ElMessage({
          type: 'error',
          dangerouslyUseHTMLString: true,
          message: `<div>提交失败，请检查以下字段：<br/>${errorMessages.join('<br/>')}</div>`
        })
      } catch (e) {
        console.error('解析错误信息失败:', e);
        ElMessage.error(error.message || (isEdit.value ? '更新排班失败' : '创建排班失败'))
      }
    } else {
      // 显示一般错误
      ElMessage.error(error.message || (isEdit.value ? '更新排班失败' : '创建排班失败'))
    }
  } finally {
    submitLoading.value = false
  }
}

// 重试获取医生ID
const retryGetDoctorId = async () => {
  doctorIdFailed.value = false
  await getSchedules()
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/portal/login')
}

// 组件挂载时
onMounted(() => {
  // 获取排班数据
  getSchedules()
  
  // 获取科室信息
  getDoctorDepartment()
})

// 自定义日期格式化函数，更好地显示中文日期
const formatDateDisplay = (dateStr) => {
  if (!dateStr) return '';
  
  try {
    let normalizedDate;
    
    // 处理ISO格式日期字符串（包含T00:00:00的情况）
    if (typeof dateStr === 'string') {
      if (dateStr.includes('T')) {
        normalizedDate = dateStr.split('T')[0]; // 截取T前面的部分
      } else {
        normalizedDate = dateStr;
      }
    } else {
      // 处理日期对象
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return dateStr;
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      normalizedDate = `${year}-${month}-${day}`;
    }
    
    // 解析格式化后的日期
    const parts = normalizedDate.split('-');
    if (parts.length === 3) {
      const date = new Date(`${parts[0]}-${parts[1]}-${parts[2]}`);
      if (!isNaN(date.getTime())) {
        // 获取月和日
        const month = parseInt(parts[1]);
        const day = parseInt(parts[2]);
        
        // 获取星期几
        const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
        const weekDay = weekDays[date.getDay()];
        
        return `${month}-${day} (${weekDay})`;
      }
    }
    
    // 无法解析时返回原始日期
    return normalizedDate;
  } catch (e) {
    console.error('日期格式化错误:', e);
    return dateStr;
  }
}
</script>

<style scoped>
.doctor-schedule {
  margin-bottom: 20px;
  width: 100%;
  overflow-x: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.time-slot-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  flex-wrap: wrap;
  gap: 5px;
}

.time-slot-detail {
  margin-left: 8px;
  color: #606266;
  white-space: nowrap;
}

.capacity-info {
  margin-left: 5px;
  color: #909399;
  font-size: 12px;
}

.remaining-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  white-space: nowrap;
}

.remaining-item span {
  margin-right: 8px;
  color: #606266;
}

.pagination-container {
  text-align: right;
  padding-top: 20px;
}

.time-slots-container {
  margin-bottom: 10px;
}

.time-slot-hint {
  font-size: 14px;
  font-weight: bold;
  margin: 16px 0 8px;
  color: #606266;
}

.time-slot-hint:first-child {
  margin-top: 0;
}

.time-slot-group {
  margin-bottom: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.time-slot-group :deep(.el-checkbox-button) {
  margin-right: 0;
  margin-bottom: 0;
}

.form-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.cancel-warning {
  margin-bottom: 20px;
}

.error-container {
  padding: 20px;
}

.error-actions {
  text-align: right;
  margin-top: 20px;
}

/* 新增的样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
  white-space: nowrap;
}

:deep(.el-table) {
  font-size: 14px;
  width: 100%;
}

:deep(.el-table__body) {
  width: 100% !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__cell) {
  padding: 8px;
  word-break: break-word;
}

:deep(.el-table .cell) {
  padding: 0 8px;
}

:deep(.el-button--small) {
  padding: 6px 12px;
  min-height: 28px;
}

:deep(.el-table-column--action .cell) {
  overflow: visible;
}

.date-display {
  font-weight: 500;
  white-space: nowrap;
}

@media (max-width: 1200px) {
  .filter-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-container .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
  }
}
</style> 